package com.example.statemachine.service;

import com.example.statemachine.core.EventEnum;
import com.example.statemachine.entity.StateTransitionLog;
import com.example.statemachine.event.StateChangeEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

@Slf4j
@Service
public class StateTransitionLogService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Transactional
    public void recordTransitionLog(StateChangeEvent event) {
        try {
            StateTransitionLog logEntity = new StateTransitionLog();
            logEntity.setBusinessId(event.getContext().getBusinessId());
            logEntity.setFromState(event.getFromState());
            logEntity.setToState(event.getToState());

            // 确保event不为null
            EventEnum eventEnum = event.getContext().getEvent();
            if (eventEnum == null) {
                log.warn("状态转换事件为null，使用默认事件UNKNOWN");
                // 可以定义一个默认事件，或者根据业务逻辑处理
                eventEnum = EventEnum.MODIFY; // 或者创建一个UNKNOWN事件
            }
            logEntity.setEvent(eventEnum);

            logEntity.setOperator(event.getContext().getOperator());
            logEntity.setOperateTime(event.getContext().getOperateTime());
            logEntity.setRemark(event.getContext().getRemark());

            if (event.getContext().getExtraParams() != null) {
                logEntity.setExtraData(objectMapper.writeValueAsString(event.getContext().getExtraParams()));
            }

            entityManager.persist(logEntity);
            log.info("记录状态转换日志成功: {} -> {} -> {}",
                    event.getFromState(), event.getToState(), eventEnum);

        } catch (Exception e) {
            log.error("记录状态转换日志失败: {} -> {}",
                    event.getFromState(), event.getToState(), e);
            // 这里不要抛出异常，避免影响主业务流程
            // 可以记录到专门的错误日志或发送告警
        }
    }
}